package com.util;

import java.awt.HeadlessException;
import java.io.UnsupportedEncodingException;

import org.hibernate.HibernateException;
import org.hibernate.Query;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;


import  java.util.List;

import com.bean.Use;


public class UseUtil {
	public static SessionFactory currentSession() {
		SessionFactory sf= null;
		try {
			Configuration cfg = new Configuration().configure();
			 sf = cfg.buildSessionFactory();
			if (sf != null) {
				System.out.println("SessionFactory is ok");
			}
					} catch (Exception e) {
			System.out.println("sf error>>>" + e);
		}
		return sf;
	}
	public static void sfClose(SessionFactory sf){
		if(sf!=null){
			sf.close();
			System.out.println("sf is closed");
		}else{
			System.out.println("sf is opening");
		}
	}
	public static void findExcude( String name){
		boolean v=false;
		try {
			Session session = currentSession().openSession();
			if(session==null){
				System.out.println("findExcude session is null");
			}
			Transaction tx = session.beginTransaction();
			Query a= session.createQuery("from Use u where u.name=:name ");
			a.setParameter("name",name);
			//System.out.print(a.toString()); 
			List ll =  a.list();
			if(!ll.isEmpty()){
				System.out.print("iaaaaaaaa");
			}
			System.out.println(ll);
			tx.commit();
		} catch (HibernateException e) {
			System.out.println("findExcude error"+e);
		}
	}
	public static void excude(Use use){
		try {
			Session session = currentSession().openSession();
			if(session!=null){
				System.out.println("excude Session is ok!");
			}
			Transaction tx = session.beginTransaction();
			session.save(use);
			tx.commit();
			sfClose(currentSession());
			session.close();

		} catch (Exception e) {
			System.out.println("Session is null");
		}
	}
	public static String str(String str) throws UnsupportedEncodingException {
		if (str == null) {
			str = "";
		}
		return new String(str.getBytes("iso-8859-1"), "UTF-8");
	}
	public static void addUse(String name,String mail, String password){
		try {
			Use use = new Use();
			String na = str(name);
			int id = (int) (Math.random() * 10000)
					+ (int) (Math.random() * 1000)*(int) (Math.random() * 1000);
			use.setId(id);
			use.setName(na);
			use.setMail(mail);
			use.setPassword(password);
			excude(use);
		} catch (Exception e) {
			System.out.println("addUse error" + e);
		}
		
	}
	public static boolean chkName(String name){
		
	return true;	
	}
	public static void main(String args[]) {
		//addUse("a","b","v");
		findExcude("a");
	}
}
